var express = require('express');
var router = express.Router();
var open = require('../../utils/mongodb').open
var bcrypt=require('../../utils/bcrypt')
var jwt = require('../../utils/jwt')


router.post('/', function(req, res, next) {
console.log('login');

//1.获取username,password,
let {username,password}=req.body;
//2.设定必传参数
if(!username||!password){
    res.send({
        err:1,
        msg:'用户名密码为必传参数'
    })
    return;
}
//3.兜库 open
open({
    collectionName:'user'
}).then(
    ({collection,client})=>{
        collection.find({username}).toArray((err,result)=>{
            if(err){
                res.send({
                    err:1,
                    msg:'集合操作失败',messag:err
                })
                client.close()
            }else{
                 //校验用户名username是否存在
                if(result.length>0){
                    //校验密码  解密 对比
                  if( bcrypt.compareSync(password,result[0].password)){
                    // 成功（生成token)
                   let token = jwt.sign({username,_id:result[0]._id});
                   delete result[0].username;
                   delete result[0].password;
                   res.send({err:0,msg:'登录成功',data:result[0],token});
                   client.close();
                  }else{
                      //失败 
                    res,send({err:1,msg:'用户名或密码不存在'})
                    client.close()
                  }

                    
                }else{
                    res,send({err:1,msg:'用户名或密码不存在'})
                    client.close()
            }
           }
        })
    }
).catch(
    err=>res.send({
        err:1,
        msg:'库链接失败'
    })
)

});

module.exports = router;